// 付款登记弹窗
<template>
  <div class="addDialog">
    <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" @close="handleDialogClosed">
      <el-form ref="dialogForm" :rules="rules" :model="formData">
        <el-row :gutter="40">
          <el-col :span="24">
            <h4 class="dialogItemTitle">付款信息</h4>
          </el-col>

          <el-col :span="12" class="listFormItem">
            <el-form-item label="工程名称" prop="engineeringName" class="listFormItem">
              <el-button class="add" type="primary" size="mini" @click="chooseEngineering" v-if="type == 'add'">选择工程合同</el-button>
              <el-input v-model="formData.engineeringName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物业名称" class="full" prop="propertyName">
              <el-input v-model="formData.propertyName" readonly />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="付款方式" class="full" prop="paymentWay">
              <el-input v-model="formData.paymentWay" readonly type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <h4 class="dialogItemTitle">本次付款信息</h4>
          </el-col>
          <el-col :span="24">
            <div class="inlineInputGroup">
              <span>第</span>
              <el-form-item class="full" prop="payNumber">
                <el-input :readonly="type === 'preview'" v-model.number="formData.payNumber" />
              </el-form-item>
              <span>次 付款支付日期</span>
              <el-form-item class="full" prop="payDate">
                <el-date-picker type="datetime" v-model="formData.payDate" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请输入支付日期" :readonly="isReadonly" />
              </el-form-item>
              <span>支付金额</span>
              <el-form-item class="flexInputItem" prop="payAmount">
                <el-input oninput="value = value.replace(/[^0-9.]/g,'')" :readonly="type === 'preview'" v-model="formData.payAmount">
                  <i slot="suffix" class="el-input__icon">元</i>
                </el-input>
                <em v-if="residueAmount != ''">未付金额: {{residueAmount}}元</em>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="24">
            <h4 class="dialogItemTitle">历史付款记录</h4>
            <el-table ref="multipleTable" align="center" :data="payHistory">
              <el-table-column label="单位类型" prop="payObjectType">
                <template slot-scope="scope">{{getCompanyName(scope.row.payObjectType)}}</template>
              </el-table-column>
              <el-table-column label="单位名称" prop="payObject" />
              <el-table-column label="付款次数" prop="payNumber" />
              <el-table-column label="付款金额" prop="payAmount" />
              <el-table-column label="付款日期" prop="payDate" />
            </el-table>
          </el-col>
        </el-row>
      </el-form>

      <!-- 工程选择弹窗 -->
      <propertyChooseDialog ref="engineeringChoose" dialogType="payment" @changeProperty="handleEngineeringChange" />
      <div slot="footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button v-if="type !== 'preview'" type="primary" v-throttle="[save]" :loading="saveLoading">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import propertyChooseDialog from "@/views/wy-operate/components/propertyChooseDialog";
import { changeOperationpayitem, getPaymentHistory, } from "@/views/wy-operate/api/repair.js";
import { mapState } from "vuex";
export default {
  name: "addDepartment",
  components: {
    propertyChooseDialog,
  },
  inject: ["initList"],
  data () {
    var validateResidueAmount = (rule, value, callback) => {
      if (parseFloat(value) > parseFloat(this.residueAmount)) {
        callback(new Error('付款金额不能超过未付金额'))
      }
      callback()
    };
    return {
      type: "add", //弹窗类型，默认新增
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        //工程名称(不可编辑)
        engineeringName: "",
        // 物业名称(不可编辑)
        propertyName: "",
        // 付款方式(不可编辑)
        paymentWay: "",
        //付款日期
        payDate: "",
        //付款次数
        payNumber: "",
        //付款金额
        payAmount: "",
        // 付款id(不可编辑)
        payId: "",
        // 支付对象（施工单位名称）(不可编辑)
        payObject: "",
        // 支付对象类型（供应商类型）(不可编辑)
        payObjectType: "",
      },
      // 校验规则
      rules: {
        engineeringName: [{ required: true, message: "工程名称不能为空", trigger: "blur" }],
        propertyName: [{ required: true, message: "工程名称不能为空", trigger: "blur" }],
        paymentWay: [{ required: true, message: "付款方式不能为空", trigger: "blur" },],
        payNumber: [
          { required: true, message: "付款次数不能为空", trigger: "blur" },
          { type: 'number', min: 1, message: "付款次数不能小于0", trigger: "blur" },
        ],
        payDate: [{ required: true, message: "支付日期不能为空", trigger: "blur" },],
        payAmount: [
          { required: true, message: "支付金额不能为空", trigger: "blur" },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的金额", trigger: "blur" },
          { validator: validateResidueAmount, trigger: "blur" },
        ],
      },
      // 保存按钮loading
      saveLoading: false,
      // 付款记录
      payHistory: [],
      // 付款总金额
      totalAmount: '',
      // 未付金额
      residueAmount: '',
    };
  },
  computed: {
    ...mapState({
      // 公司类型列表
      companyDict: (state) =>
        state.dict.find((item) => item.type === "provider_type") || {
          children: [],
        },
    }),
    // 弹窗标题计算
    dialogTitle () {
      return {
        preview: "查看",
        edit: "编辑",
        add: "新增",
      }[this.type];
    },
    // 判断是否只读
    isReadonly () {
      return ["preview"].includes(this.type);
    },
    // 获取未付金额
    // residueAmount() {
    //   if(this.payHistory.length) {
    //     return this.payHistory[0].residueAmount
    //   } else {
    //     return this.totalAmount
    //   }
    // },
  },
  methods: {
    //开启弹窗
    show ({ type, data = {} }) {
      if (["preview", "edit"].includes(type)) {
        this.formData = data;
        this.getPaymentHistory(data.payId);
      }
      this.type = type;
      this.dialogVisible = true;
    },
    // 提交新增
    save () {
      if (["edit", "add"].includes(this.type)) {

        this.$refs.dialogForm.validate((valid) => {
          const { payNumber, payAmount, payDate, payId, payObject, payObjectType, itemId } = this.formData;
          let params = {
            payNumber,
            payAmount: parseFloat(payAmount),
            payDate,
            payId,
            payObject,
            payObjectType,
            itemId: this.type == 'add' ? '' : itemId
          };
          if (valid) {
            this.saveLoading = true;
            changeOperationpayitem(params, this.type).then((res) => {
              if (res.data.code == 0) {
                this.$message.success(`${this.dialogTitle}成功!`);
                this.initList({ current: 1, engineeringName: "" });
                this.dialogVisible = false;
              } else {
                this.$message.error(res.data.msg)
              }
            }).finally(() => {
              this.saveLoading = false;
            });
          }

        });
      }
    },

    // 选择工程名称
    chooseEngineering () {
      this.$refs.engineeringChoose.show("payitem");
    },
    // 监听工程改变
    handleEngineeringChange (data) {
      const { payId, engineeringName, propertyName, unitType, unitName, payMethod, totalAmount } = data;
      //获取付款记录
      payId && this.formData.payId != payId && this.getPaymentHistory(payId);

      this.residueAmount = this.payHistory.length ? this.payHistory[0].residueAmount : totalAmount

      this.formData = {
        ...this.formData,
        engineeringName,
        payId,
        propertyName,
        paymentWay: payMethod,
        payObject: unitName,
        payObjectType: unitType,
      };

      this.totalAmount = totalAmount
    },
    // 获取付款记录
    getPaymentHistory (payId) {
      getPaymentHistory(payId).then((res) => {
        if (res.data.code == 0) {
          this.payHistory = res.data.data;
          this.residueAmount = res.data.data.length ? res.data.data[0].residueAmount : this.totalAmount
        }
      });
    },
    // 获取公司单位类型
    getCompanyName (unitType) {
      let companyType = this.companyDict.children.find(
        (item) => item.value == unitType
      );
      return companyType ? companyType.label : "";
    },
    // 弹窗关闭初始化
    handleDialogClosed () {
      for (var i in this.formData) {
        this.formData[i] = ''
      }
      this.payHistory.length = 0
      this.totalAmount = ''
      this.saveLoading = false;
      this.residueAmount = ''
      this.$refs.dialogForm.resetFields()
    }
  },
};
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.addDialog {
  /deep/ .el-date-editor--datetime {
    width: 100%;
  }
}
.inlineInputGroup {
  display: flex;
  align-items: center;
  & > span {
    padding: 0 0.5em;
  }
  .el-date-editor {
    width: 200px;
  }
  .el-form-item {
    margin: 0;
  }
  span {
    line-height: 40px;
  }
}
/deep/ .flexInputItem {
  .el-form-item__content {
    display: flex;
    align-items: center;
    .el-input {
      width: 200px;
    }
    & > em {
      display: inline-block;
      font-style: normal;
      font-size: 13px;
      line-height: 1;
      margin-left: 10px;
    }
  }
}
</style>
